import { _decorator, Node, Vec3, UITransform, Vec2 } from 'cc';

export function v2ToV3(v2: Vec2, out: Vec3 = new Vec3()) {
    out.x = v2.x
    out.y = v2.y
    return out
}
/**转换一个世界坐标到节点的局部坐标 */
export function convertToNodeSpaceAR(parent: Node, pos: Vec3, out?: Vec3) {
    const uiTransform = parent.getComponent(UITransform)
    return uiTransform.convertToNodeSpaceAR(pos, out)
}


export function setNodeScale(node: Node, scale: number) {
    node.setScale(scale, scale, scale)
}

export function setNodeScaleX(node: Node, scale: number) {
    node.setScale(scale, node.scale.y, node.scale.z)
}

export function setNodeScaleY(node: Node, scale: number) {
    node.setScale(node.scale.x, scale, node.scale.z)
}

export function setNodePosX(node: Node, x: number) {
    node.setPosition(x, node.position.y, node.position.z)
}

export function setNodePosY(node: Node, y: number) {
    node.setPosition(node.position.x, y, node.position.z)
}
/**
 * 给枚举值添加前缀，变成${prefix}_${value}的格式
 * *只能用在值是数字的枚举上
 * @param e //枚举
 * @param prefix //前缀
 * @param canRepeatSet //是否允许重复设置
 */
export function setEnumPrefix(e: any, prefix: string | number, canRepeatSet = false) {
    /*@ts-ignore */
    if (!setEnumPrefix.preFixMap) {
        /*@ts-ignore */
        setEnumPrefix.preFixMap = {}
    }
    /*@ts-ignore */
    if (!canRepeatSet && setEnumPrefix.preFixMap[prefix]) {
        console.error(e, prefix);
        throw new Error("枚举前缀重复");
    }
    /*@ts-ignore */
    setEnumPrefix.preFixMap[prefix] = e

    let keys = Object.keys(e).filter(key => typeof e[key] === "number")
    keys.forEach(key => {
        const value = e[key]
        const newValue = `${prefix}_${value}`
        Reflect.deleteProperty(e, value)
        e[key] = newValue
        e[newValue] = key
    })
}

/**延时 */
export function delay(ms: number) {
    return new Promise((r) => {
        setTimeout(() => {
            r(null)
        }, ms);
    })
}

/**
* 获取本地时间戳，单位毫秒（注：有可能被玩家修改）
* @returns  {number} 时间戳，单位毫秒
*/
export function getClientTimestampMS(): number {
    return Math.floor(Date.now())
}

/**
 * 获取当前时间戳，单位秒
 * @returns  {number} 时间戳，单位秒
 */
export function getTimestampS(): number {
    return Math.floor(getClientTimestampMS() / 1000);
}

export function isNewDay(oldTime: number, newTime: number): boolean {
    const oldDate = new Date(oldTime);
    const newDate = new Date(newTime);
    return newDate.getFullYear() > oldDate.getFullYear()
        || newDate.getFullYear() >= oldDate.getFullYear() && (newDate.getMonth() + 1) > (oldDate.getMonth() + 1)
        || newDate.getFullYear() >= oldDate.getFullYear() && (newDate.getMonth() + 1) >= (oldDate.getMonth() + 1) && newDate.getDate() > oldDate.getDate()
}